package com.zs.netlibrary.http.request.impl.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.zs.netlibrary.http.RequestContent;
import com.zs.netlibrary.http.request.IRequest;
import com.zs.netlibrary.http.request.impl.okhttp.cookie.CookiesManager;
import com.zs.netlibrary.http.result.IResponseResult;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * OKHttp网络框架的实现
 * Created by sheng on 2017/8/15.
 */
public class OkRequest implements IRequest {
    private static String TAG = "OkRequest";
    private OkHttpClient mOkHttpClient;
    private Handler mHandler;

    public OkRequest() {
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .cookieJar(new CookiesManager())
                .build();
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void sendGetRequest(final RequestContent action) {
        //2,创建一个Request
        final Request request = new Request.Builder().url(action.getRequestUrl()).build();
        //3,创建一个call对象
        Call call = mOkHttpClient.newCall(request);

        //4,将请求添加到调度中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new IResponseResult(action).onFailed();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String message = response.body().string();
                    new IResponseResult(action).onSeccess(message);
                }
            }
        });
    }

    @Override
    public void sendPostRequest(final RequestContent action) {
        //2,创建Request
        FormBody.Builder builder = new FormBody.Builder();
        Map<String, String> map = action.getParameters();
        if(map != null && map.size() > 0){
            Iterator it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = entry.getKey().toString();
                String value = entry.getValue().toString();
                builder.add(key, value);
            }
        }

        FormBody formBody = builder.build();
        Request request = new Request.Builder().url(action.getRequestUrl()).post(formBody).build();
        //3，创建call对象并将请求对象添加到调度中
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        new IResponseResult(action).onFailed();
//                        action.getCallback().onFailed();
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String body = response.body().string();
                Log.i(TAG, body);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            new IResponseResult(action).onSeccess(body);
//                            action.getCallback().onResponse(body);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

        });
    }

    @Override
    public void cancelAllRequests(boolean mayInterrupIfRunning) {

    }

    @Override
    public void setTimeOut(int value) {

    }

    @Override
    public void dowmloadFile(final RequestContent action) {
        FormBody.Builder builder = new FormBody.Builder();
        Map<String, String> map = action.getParameters();
        if(map != null && map.size() > 0){
            Iterator it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = entry.getKey().toString();
                String value = entry.getValue().toString();
                builder.add(key, value);
            }
        }

        FormBody formBody = builder.build();
        Request request = new Request.Builder().url(action.getRequestUrl()).post(formBody).build();
        //3，创建call对象并将请求对象添加到调度中
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        new IResponseResult(action).onFailed();
//                        action.getCallback().onFailed();
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final InputStream body = response.body().byteStream();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            new IResponseResult(action).onSeccess(body);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

        });
    }
}
